import React, { useEffect, useState } from "react";
import axios from "../../request/axios";
import { Input } from "antd";
import { Button, Avatar, Modal } from "antd";
import { Form } from "antd";
import type { FormProps } from "antd";
import InfiniteScroll from 'react-infinite-scroll-component';
import { Divider, List, Skeleton } from 'antd';
import replaceWord from '../../utils/sensitivity'
import _ from 'lodash'

type FieldType = {
  account?: string;
  password?: string;
};

const { TextArea } = Input;
function Comment() {
  const [from] = Form.useForm();
  const [text,settext] = useState('发送')
  const [comments, setComments] = useState([]);
  const [value, setvalue] = useState<string>('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const getlist = () => {
     axios({
      url: "http://blogapi.shbwyz.com/article/274",
      method: "get",
    }).then((res) => {
      console.log(res.data.comments);
      setComments(res.data.comments);
    });
  }
  useEffect(() => {
   getlist()
  }, []);

  const token = localStorage.getItem("token");

  useEffect(() => {
    if (token) {
      settext("发送");
    }else{
        settext("登录")
    }
  }, [token]);
 
  const fs = _.debounce(() => {
    if (!token) {
      setIsModalOpen(true);
    }else{
        axios({
            url:'http://blogapi.shbwyz.com/discuss',
            method:'post',
            data:{
                userId:47529555,
                content:replaceWord(value),
                articleId:274,
            }
        }).then(res=>{
            console.log(res)
            getlist()
            setvalue('')
        })
    }
  },500);

  const handleOk = () => {
    from.submit();
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    axios({
      url: "http://blogapi.shbwyz.com/login",
      method: "post",
      data: {
        account: values.account,
        password: values.password,
      },
    }).then((res) => {
      console.log(res);
      localStorage.setItem("token", res.data.token);
      localStorage.setItem("username", res.data.username);
    });
  };

   const loadMoreData = () => {
    if (loading) {
      return;
    }
    setLoading(true);
    fetch('http://blogapi.shbwyz.com/article/274')
      .then((res) => {
        setComments([...comments, ...res.data.comments]);
        setLoading(false);
      })
  };

  useEffect(() => {
    loadMoreData();
  }, []);

  return (
    <div>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={from}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="account"
            name="account"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="password"
            name="password"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
      <div style={{ display: "flex", height: "100px" }}>
        <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=1" />
        <TextArea
          style={{ height: "100%" }}
          rows={4}
          placeholder="平等表达，友善交流"
          maxLength={100}
          value={value}
          onChange={(e) => {
            setvalue(e.target.value);
          }}
        />
        <Button style={{ height: "100%" }} type="primary" onClick={fs}>
          {text}
        </Button>
      </div>
      <InfiniteScroll
        dataLength={comments.length}
        next={loadMoreData}
        hasMore={comments.length < 40}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain>已全部加载完毕 🤐</Divider>}
        scrollableTarget="scrollableDiv"
      >
      {comments &&
        comments?.map((item) => {
          return (
            <div
              style={{ display: "flex", marginTop: "10px", background: "#ccc" }}
              key={item.id}
            >
              <Avatar
                src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${item.id}`}
              />
              &nbsp;&nbsp;&nbsp;
              <div>
                <p>
                  <span>{item.user.username}</span>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <span>{item.user.email}</span>
                </p>
                <p>{item.content}</p>
                <p>{item.createdAt}</p>
              </div>
            </div>
          );
        })}
        </InfiniteScroll>
    </div>
  );
}

export default Comment;
